package com.ylbh.modules.sys.controller;


import com.ylbh.common.utils.CommonResult;
import com.ylbh.common.utils.DateHelper;
import com.ylbh.common.utils.OSSClient;
import com.ylbh.common.utils.Ref;
import com.ylbh.common.utils.ueditor.ActionEnter;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * 用于处理关于ueditor插件相关的请求
 * @date 2017-11-29
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/ueditor")
public class UeditorController {
	@Value("${url.shoppingMainImage}")
	private String uploadHost;

	@RequestMapping(value = "/uploadImg")
	@ResponseBody
	public CommonResult<String> uploadImg(@RequestBody MultipartFile img){
		String originalFilename = img.getOriginalFilename();
		if (originalFilename.contains("spaceball.gif")) {
			// 淘宝默认的gif，上传导致黑屏
			return Ref.error("");
		}
		if(img==null){
			return Ref.error("上传图片时，图片为空");
		}
		OSSClient ossClient = new OSSClient();
		try {
			String suffix = "33307/"+ DateHelper.getDate();
			String name = ossClient.uploadCompressImg2Oss(img,"consumer/upload/store/",suffix);
			return Ref.ok(uploadHost+"upload/store/"+suffix+"/"+name);
		} catch (Exception e) {
			e.printStackTrace();
			return Ref.error("上传图片失败");
		}
	}

	@RequestMapping(value = "/exec")
	@ResponseBody
	public String exec(HttpServletRequest request) throws UnsupportedEncodingException, JSONException {
		request.setCharacterEncoding("utf-8");
		String rootPath = request.getServletContext().getRealPath("/");
		return new ActionEnter( request, rootPath ).exec();
	}

}
